#include <mosquitto.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
{
    printf("主题：%s 内容：%s\n", msg->topic, (char *)msg->payload);
}

int main(void)
{
    struct mosquitto *mosq;
    int rc;
    // 初始化mosquitto库
    mosquitto_lib_init();

    // 创建客户端对象
    mosq = mosquitto_new(NULL, true, NULL);
    if (mosq == NULL)
    {
        fprintf(stderr, "Error: Out of memory.\n");
        return -1;
    }

    // 连接MQTT服务器
    rc = mosquitto_connect(mosq, "47.109.74.191", 1883, 60);
    if (rc != MOSQ_ERR_SUCCESS)
    {
        mosquitto_destroy(mosq);
        fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
        return -1;
    }
    printf("连接MQTT服务器成功\n");

    // 订阅主题
    rc = mosquitto_subscribe(mosq, NULL, "temp", 0);
    if (rc != MOSQ_ERR_SUCCESS)
    {
        fprintf(stderr, "Error subscribing: %s\n", mosquitto_strerror(rc));
        /* We might as well disconnect if we were unable to subscribe */
        mosquitto_disconnect(mosq);
    }

    // 设置读取数据的回调函数
    mosquitto_message_callback_set(mosq, on_message);

    // 进入循环
    mosquitto_loop_forever(mosq, -1, 1);
}
